//
//  BBUploadImage.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/11/30.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import UIKit

class BBUploadImage: NSObject {
    static let tools:BBUploadImage = {
        let t = BBUploadImage()
        return t
    }()
    
    //获取单例
    class func shareBBUploadImage()->BBUploadImage{
        return tools
    }
    

    
    private func compressImageSize(_ image: UIImage, toByte maxLength: Int) -> UIImage {
        guard var data = image.jpegData(compressionQuality: 1) else { return image }
        var resultImage: UIImage = image
        var lastDataLength: Int = 0
        while data.count > maxLength, data.count != lastDataLength {
            lastDataLength = data.count
            let ratio: CGFloat = CGFloat(maxLength) / CGFloat(data.count)
            let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),
                                      height: Int(resultImage.size.height * sqrt(ratio)))
            UIGraphicsBeginImageContext(size)
            resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            resultImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            data = resultImage.jpegData(compressionQuality: 1)!
        }
        return resultImage
    }
    
    public func upload(path:String,params:[String:AnyObject?],image:UIImage,maxSizeByte:Int,finsih:@escaping (_ obj:Bool)->()){
        let imageTem = compressImageSize(image, toByte: maxSizeByte)
        let data = imageTem.pngData()
        AFNetWorkManager.shareNetworkTools().post(path, parameters: params, constructingBodyWith: { (fromData) in
            fromData.appendPart(withFileData: data!, name: "upload_file", fileName: "png", mimeType: "application/octet-stream")
        }, progress: { (nil) in
            
        }, success: { (_, json) in
            finsih(true)
        }) { (_, error) in
            finsih(false)
        }
    }
}
